package com.example.myapplication.ui.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.myapplication.network.api.ProductApiService
import com.example.myapplication.network.api.ProductDetail
import com.example.myapplication.network.core.NetworkResult
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch

class ProductDetailViewModel : ViewModel(){
    private val _productDetailState = MutableStateFlow<NetworkResult<ProductDetail>>(NetworkResult.Loading())
    val productDetailState = _productDetailState.asStateFlow()

    init {
        getProductDetails()
    }

    //获取商品详情数据
    fun getProductDetails(){
        viewModelScope.launch {
            _productDetailState.value = NetworkResult.Loading()
            try {
                val produtDetail = ProductApiService.getInstance().getProductDetail()
                _productDetailState.value = NetworkResult.Success(produtDetail)
            }catch (e: Exception){
                _productDetailState.value = NetworkResult.Error("商品详情数据加载失败")
            }
        }
    }
}